﻿using Common;
using Dm;
using Dm.filter;
using FCT551.Base;
using FCT551.Helper;
using FCT551.Models;
using FCT551.Procedure;
using FCT551.Views;
using LiveCharts;
using LiveCharts.Wpf;
using NewDevice;
using NewDevice.RS232;
using NewDevice.RS485;
using OfficeOpenXml;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Xml.Serialization;
using Color = System.Windows.Media.Color;

namespace FCT551.ViewModels
{
    public class HomeViewModel : NotifyPorperChanged
    {
        /// <summary>
        /// 加载全局变量
        /// </summary>
        private HomeView _homeView;//主界面

        public static Action<string, string, string> UpdateConfigName;
        public static Action InitStation;
        public static ChangeUniformBackgroudHandler _ChangeUniform;
        public static StartHandler? _Start;
        public static EmsStopHandler? EmsStop;
        public static ResetHandler _Reset;
        private OperateView _operateView;//员工操作界面
        private UserLoginView _userLoginView;//用户登录注册界面
        private IODebugView _ioDebugView;//io调试界面
        private CollectDateView _collectDateView;//采集数据界面
        private MotionDebugView _motionDebugView;//电机调试界面
        private ConfigManageView _configManageView;//配置管理界面
        private CapacityStatisticsView _capacityStatisticsView;//产能管理界面
        private MesConfigView _mesConfigView;//选择mes配置界面
        private CancellationTokenSource _showTimeTaskTokenSource;//实时显示时间Task的token
        private readonly Lock _updateMessageLock;//显示日志锁

        public HomeViewModel(HomeView homeView, string sn, string Msg)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            //默认启用操作界面
            _homeView = homeView;
            _operateView = new();
            MainView = _operateView;
            //初始化命令
            ExitCommand = new Command() { ExeAction = new Action<object>(ExitCmd) };
            ShowOperateViewCommand = new Command() { ExeAction = new Action<object>(ShowOperateViewcmd) };
            ShowUserLoginViewCommand = new Command() { ExeAction = new Action<object>(ShowUserLoginViewcmd) };
            ShowIODebugViewCommand = new Command() { ExeAction = new Action<object>(ShowIODebugViewcmd) };
            ShowConfigManagerViewCommand = new Command() { ExeAction = new Action<object>(ShowConfigManagerViewcmd) };
            ShowCollectDataViewCommand = new Command() { ExeAction = new Action<object>(ShowCollectDataViewCmd) };
            ShowMotionDebugViewCommand = new Command() { ExeAction = new Action<object>(ShowMotionDebugViewcmd) };
            ShowMesConfigViewCommand = new Command() { ExeAction = new Action<object>(ShowMesConfigViewCmd) };
            InitSysCommand = new Command() { ExeAction = new Action<object>(InitSyscmd) };
            ShowCapacityCommand = new Command() { ExeAction = new Action<object>(ShowCapacitycmd) };
            //全局变量初始化
            MessageLists = new ObservableCollection<MsgInfo>();
            _updateMessageLock = new();
            _showTimeTaskTokenSource = new CancellationTokenSource();
            //委托绑定

            OperaViewModel.updatemessage += UpdateMessage;
            CollectDataViewModel.updatemessage += UpdateMessage;
            CapacityStatisticsViewModel.updatemessage += UpdateMessage;
            ConfigManageViewModel.updatemessage += UpdateMessage;
            MesConfigView.updatemessage += UpdateMessage;
            SocketClient.updatemessage += UpdateMessage;
            OperaViewModel.updatedata += UpdateData;
            OperaViewModel._Unlogin += ShowUserLoginViewcmd;
            //开始显示最下栏产品序列号，到期日期，当前时间等
            ShowProdeceLisence(sn, Msg);
        }

        #region 配置绑定属性

        private object _mainView;

        public object MainView
        {
            set
            {
                _mainView = value;
                this.SetProperty();
            }
            get
            {
                return _mainView;
            }
        }

        private ObservableCollection<MsgInfo> messageLists;

        public ObservableCollection<MsgInfo> MessageLists
        {
            set
            {
                messageLists = value;
                this.SetProperty();
            }
            get
            {
                return messageLists;
            }
        }

        private string produceSn;

        public string ProduceSn
        {
            set
            {
                produceSn = value;
                this.SetProperty();
            }
            get
            {
                return produceSn;
            }
        }

        private string aLLCapacity;

        //历史产能
        public string ALLCapacity
        {
            set
            {
                aLLCapacity = value;
                this.SetProperty();
            }
            get
            {
                return aLLCapacity;
            }
        }

        private string monthCapacity;

        public string MonthCapacity
        {
            set
            {
                monthCapacity = value;
                this.SetProperty();
            }
            get
            {
                return monthCapacity;
            }
        }

        private string produceDatetime;

        public string ProduceDatetime
        {
            set
            {
                produceDatetime = value;
                this.SetProperty();
            }
            get
            {
                return produceDatetime;
            }
        }

        private string produceDays;

        public string ProduceDays
        {
            set
            {
                produceDays = value;
                this.SetProperty();
            }
            get
            {
                return produceDays;
            }
        }

        private string nowTiming;

        public string NowTiming
        {
            set
            {
                nowTiming = value;
                this.SetProperty();
            }
            get
            {
                return nowTiming;
            }
        }

        private string _useLoginbtnContent = "请登录";

        public string UseLoginbtnContent
        {
            set
            {
                _useLoginbtnContent = value;
                this.SetProperty();
            }
            get
            {
                return _useLoginbtnContent;
            }
        }

        private SolidColorBrush _useLoginbtnBackground = new SolidColorBrush(Colors.Red);

        public SolidColorBrush UseLoginbtnBackground
        {
            set
            {
                _useLoginbtnBackground = value;
                this.SetProperty();
            }
            get
            {
                return _useLoginbtnBackground;
            }
        }

        private SolidColorBrush _initBackground = new SolidColorBrush(Colors.Red);

        public SolidColorBrush InitBackground
        {
            set
            {
                _initBackground = value;
                this.SetProperty();
            }
            get
            {
                return _initBackground;
            }
        }

        private string _initContent = "未初始化";

        public string InitContent
        {
            set
            {
                _initContent = value;
                this.SetProperty();
            }
            get
            {
                return _initContent;
            }
        }

        private bool _initIsEnabled = true;

        public bool InitIsEnabled
        {
            set
            {
                _initIsEnabled = value;
                this.SetProperty();
            }
            get
            {
                return _initIsEnabled;
            }
        }

        private SeriesCollection _pieSeries;

        public SeriesCollection PieSeries
        {
            set
            {
                _pieSeries = value;
                this.SetProperty();
            }
            get
            {
                return _pieSeries;
            }
        }

        #endregion 配置绑定属性

        #region 配置命令属性

        private Command _exit;

        public Command ExitCommand
        {
            set
            {
                _exit = value;
            }
            get
            {
                return _exit;
            }
        }

        private Command showCapacityCommand;

        public Command ShowCapacityCommand
        {
            set
            {
                showCapacityCommand = value;
            }
            get
            {
                return showCapacityCommand;
            }
        }

        private Command _showOperateViewCommand;

        public Command ShowOperateViewCommand
        {
            set
            {
                _showOperateViewCommand = value;
            }
            get
            {
                return _showOperateViewCommand;
            }
        }

        private Command _showUserLoginViewCommand;

        public Command ShowUserLoginViewCommand
        {
            set
            {
                _showUserLoginViewCommand = value;
            }
            get
            {
                return _showUserLoginViewCommand;
            }
        }

        private Command _showIODebugViewCommand;

        public Command ShowIODebugViewCommand
        {
            set
            {
                _showIODebugViewCommand = value;
            }
            get
            {
                return _showIODebugViewCommand;
            }
        }

        private Command _showConfigManagerViewCommand;

        public Command ShowConfigManagerViewCommand
        {
            set
            {
                _showConfigManagerViewCommand = value;
            }
            get
            {
                return _showConfigManagerViewCommand;
            }
        }

        private Command _showCollectDataViewCommand;

        public Command ShowCollectDataViewCommand
        {
            set
            {
                _showCollectDataViewCommand = value;
            }
            get
            {
                return _showCollectDataViewCommand;
            }
        }

        private Command _showmotiondebugiewCommand;

        public Command ShowMotionDebugViewCommand
        {
            set
            {
                _showmotiondebugiewCommand = value;
            }
            get
            {
                return _showmotiondebugiewCommand;
            }
        }

        private Command _showMesConfigViewCommand;

        public Command ShowMesConfigViewCommand
        {
            set
            {
                _showMesConfigViewCommand = value;
            }
            get
            {
                return _showMesConfigViewCommand;
            }
        }

        private Command _initSysCommand;

        public Command InitSysCommand
        {
            set
            {
                _initSysCommand = value;
            }
            get
            {
                return _initSysCommand;
            }
        }

        #endregion 配置命令属性

        #region 绑定方法

        /// <summary>
        /// 加载配置管理界面
        /// </summary>
        /// <param name="obj"></param>
        private void ShowConfigManagerViewcmd(object obj)
        {
            try
            {
                if (Global._isInit)
                {
                    if (Global._User == null)
                    {
                        UpdateMessage("请登录用户！！", LogLevel.Error);
                        return;
                    }

                    if (Global._User.UserLevel < 2)
                    {
                        UpdateMessage("用户权限不够！！", LogLevel.Error);
                        return;
                    }
                    if (_configManageView == null)
                    {
                        _configManageView = new();
                    }

                    MainView = _configManageView;
                }
                else
                {
                    UpdateMessage("请初始化！！", LogLevel.Error);
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 加载采集数据界面
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ShowCollectDataViewCmd(object obj)
        {
            try
            {
                if (Global._isInit)
                {
                    if (Global._User == null)
                    {
                        UpdateMessage("请登录用户！！", LogLevel.Error);
                        return;
                    }

                    if (Global._User.UserLevel < 2)
                    {
                        UpdateMessage("用户权限不够！！", LogLevel.Error);
                        return;
                    }
                    if (_collectDateView == null)
                    {
                        _collectDateView = new();
                    }

                    MainView = _collectDateView;
                }
                else
                {
                    UpdateMessage("请初始化！", LogLevel.Error);
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 加载电机控制界面
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ShowMotionDebugViewcmd(object obj)
        {
            try
            {
                if (Global._isInit)
                {
                    if (Global._User == null)
                    {
                        UpdateMessage("请登录用户！！", LogLevel.Error);
                        return;
                    }

                    if (Global._User.UserLevel < 2)
                    {
                        UpdateMessage("用户权限不够！！", LogLevel.Error);
                        return;
                    }
                    if (_motionDebugView == null)
                    {
                        _motionDebugView = new();
                    }

                    MainView = _motionDebugView;
                }
                else
                {
                    UpdateMessage("请初始化！", LogLevel.Error);
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        //加载mes界面方法
        private void ShowMesConfigViewCmd(object obj)
        {
            try
            {
                if (Global._isInit)
                {
                    if (_mesConfigView == null)
                    {
                        _mesConfigView = new();
                    }

                    MainView = _mesConfigView;
                }
                else
                {
                    UpdateMessage("请初始化！", LogLevel.Error);
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 加载io调试界面方法
        /// </summary>
        /// <param name="obj"></param>

        private void ShowIODebugViewcmd(object obj)
        {
            try
            {
                if (Global._isInit)
                {
                    if (Global._User == null)
                    {
                        UpdateMessage("请登录用户！！", LogLevel.Error);
                        return;
                    }

                    if (Global._User.UserLevel < 2)
                    {
                        UpdateMessage("用户权限不够！！", LogLevel.Error);
                        return;
                    }
                    if (_ioDebugView == null)
                    {
                        _ioDebugView = new();
                    }

                    MainView = _ioDebugView;
                }
                else
                {
                    UpdateMessage("请初始化！", LogLevel.Error);
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 退出方法
        /// </summary>
        /// <param name="obj"></param>
        private async void ExitCmd(object obj)
        {
            try
            {
                IoMotion.MotionStop();
                //pwm断开
                IoMotion.OffAllPwm();
                //IO断开
                Global._PqwIoCommon.SetDo((int)CommonIODefineDo.供电12v, false);
                //气缸复位
                await IoMotion.MotionAirOut(3000);
                IoMotion.OK();
                //销毁全局变量
                Global.Dispose();

                //包含所有工作线程以及token的取消
                _showTimeTaskTokenSource?.Cancel();
                IODebugViewModel._cancellTask?.Cancel();
                CollectDataViewModel._TokenSource?.Cancel();
                Application.Current.Shutdown();
                Process.GetCurrentProcess().Kill();
            }
            catch (Exception e)
            {
                //记录退出异常日志
                MyLog.Error(e);
                //出现异常时强行终止，不推荐
                Process.GetCurrentProcess().Kill();
            }
        }

        /// <summary>
        /// 加载用户界面方法
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ShowUserLoginViewcmd(object obj)
        {
            try
            {
                if (Global._isLogin)
                {
                    //如果已登录，点击触发登出效果
                    UseLoginbtnContent = "请登录";
                    UseLoginbtnBackground = new SolidColorBrush(Colors.Red);
                    Global._User = null;
                    Global._isLogin = false;
                    UpdateMessage("退出成功");
                }
                else
                {
                    //正常登录
                    //加载用户登录界面
                    _userLoginView = new("操作员", "1");
                    if ((bool)_userLoginView.ShowDialog())
                    {
                        //登录成功
                        UpdateMessage("登录成功");
                        UseLoginbtnContent = Global._User.UserName;
                        UseLoginbtnBackground = new SolidColorBrush(Colors.Green);
                        Global._isLogin = true;
                    }
                    else
                    {
                        //登录失败
                    }
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 加载用户操作节目方法
        /// </summary>
        /// <param name="obj"></param>

        private void ShowOperateViewcmd(object obj)
        {
            try
            {
                if (_operateView == null)
                {
                    _operateView = new();
                }

                MainView = _operateView;
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 加载产能统计方法
        /// </summary>
        /// <param name="obj"></param>
        private void ShowCapacitycmd(object obj)
        {
            try
            {
                if (Global._isInit)
                {
                    if (_capacityStatisticsView == null)
                    {
                        _capacityStatisticsView = new();
                    }

                    MainView = _capacityStatisticsView;
                }
                else
                {
                    UpdateMessage("请初始化！！！", LogLevel.Error);
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 系统初始化
        /// </summary>
        /// <param name="obj"></param>

        private async void InitSyscmd(object obj)
        {
            await Task.Run(async () =>
            {
                if (!Global._isInit)
                {
                    try
                    {   //初始化客户端
                        _ = Global.client.ConnectAsync();
                        if (!await InitConfig())
                        {
                            //加载配置失败
                            UpdateMessage("配置加载失败", LogLevel.Error);
                            return;
                        }
                        if (!await InitSqlSugar())
                        {
                            //加载配置失败
                            UpdateMessage("数据库加载失败", LogLevel.Error);
                            return;
                        }

                        if (!await InitDevices())
                        {
                            //加载配置失败
                            UpdateMessage("设备加载失败", LogLevel.Error);
                            CloseAllDevice();
                            return;
                        }
                        await Task.Delay(500);
                        if (!Global.ClientISConnect)
                        {
                            //连接到服务器失败
                            UpdateMessage("连接到服务器失败", LogLevel.Error);
                            CloseAllDevice();
                            return;
                        }

                        //显示一个饼状图

                        UpdateMessage("系统初始化成功！");
                        // Global._RU_12_3040.SetStatus(true);
                        Global._isInit = true;
                        //加载所有工位
                        InitStation.Invoke();
                        //加载产品图片
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            UpdateChartData(0, 0);
                            InitBackground = new SolidColorBrush(Colors.Green);
                            UpdateConfigName?.Invoke(Global._Config.ConfigName, Global._WorkStationName, Global._WorkStationOrderName);
                            InitContent = "已初始化";
                        });
                    }
                    catch (Exception e)
                    {
                        CloseAllDevice();
                        UpdateMessage(e.Message, LogLevel.Error);
                    }
                }
            });
        }

        #endregion 绑定方法

        #region 普通方法

        /// <summary>
        /// 加载配置
        /// </summary>
        private async Task<bool> InitConfig()
        {
            try
            {
                if (!await SysConfigsHelper.ReadConfig())
                {
                    //加载配置失败
                    UpdateMessage("配置xml文件加载失败", LogLevel.Error);
                    return false;
                }
                if (!await InitSysConfigHelper.LoadMethods())
                {
                    UpdateMessage("初始化测试流程或初始化测试方法失败", LogLevel.Error);
                    return false;
                }
            }
            catch (Exception e)
            {
                //展示异常信息
                UpdateMessage(e.Message, LogLevel.Error);

                return false;
            }

            UpdateMessage("配置文件加载成功！");

            return true;
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <returns></returns>
        private async Task<bool> InitSqlSugar()
        {
            try
            {
                if (Global._sqlSugarClient == null)
                {
                    await Task.Run(() =>
                    {
                        Global._sqlSugarClient = new SqlSugarClient(new ConnectionConfig()
                        {
                            ConnectionString = "server=localhost;Database=softwaresql;Uid=root;Pwd=root123;Pooling=false",
                            DbType = DbType.MySql,
                            IsAutoCloseConnection = true //自动释放
                        });
                        //调试SQL事件，可以删掉
                        //Global._sqlSugarClient.Aop.OnLogExecuting = (sql, pars) =>
                        //{
                        //    MyLog.Debug(sql);
                        //};
                    });
                }
                else
                {
                    UpdateMessage("数据库已创建", LogLevel.Error);
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
                return false;
            }
            UpdateMessage("数据库初始化成功！！");

            return true;
        }

        /// <summary>
        /// 初始化所有设备
        /// </summary>
        /// <returns></returns>
        private async Task<bool> InitDevices()
        {
            try
            {
                //初始化电源
                OldSerialBase serialBase0 = new OldSerialBase("程控电源");
                serialBase0.Connect("COM12");
                Global._RU_12_3040 = new RU_12_3040(serialBase0, 1);
                //初始化IO模块
                if (Global._PqwIoCommon == null)
                {
                    OldSerialBase serialBase1 = new OldSerialBase("通用IO");
                    serialBase1.Connect("COM16");
                    Global._PqwIoCommon = new(serialBase1, 1, "通用IO模块");
                    Global._PqwIoCommon.DiCount = 16;
                    Global._PqwIoCommon.DoCount = 16;
                }

                //初始化电压采集卡
                Global._ZH44242G14F2_Voltage = new ZH_44242G_14F2("COM15");
                Global._ZH44242G14F2_Voltage.MeasureRange = 30;
                _ = Global._ZH44242G14F2_Voltage.StartAsync();
                //初始化电流采集卡
                Global._ZH44242G14F2_Current = new ZH_44242G_14F2("COM14", 9600);
                Global._ZH44242G14F2_Current.MeasureRange = 5;
                _ = Global._ZH44242G14F2_Current.StartAsync();
                //初始化两个电机
                OldSerialBase serialBase3 = new OldSerialBase("电机");
                serialBase3.Connect("COM11", 115200);
                Global._YPF_Y40R_1 = new(serialBase3, 1, "电机1");
                Global._YPF_Y40R_2 = new(serialBase3, 2, "电机2");
                //初始化PWM发生器
                OldSerialBase serialBase2 = new OldSerialBase("PWM发生器");
                serialBase2.Connect("COM21");
                Global._qjxPwm16 = new(serialBase2, 1, 100);
                Global._qjxPwm4 = new(serialBase2, 2, 100);
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
                return false;
            }
            UpdateMessage("设备初始化成功！！");

            return true;
        }

        /// <summary>
        /// 关闭所有设备
        /// </summary>
        public void CloseAllDevice()
        {
            Global._RU_12_3040?.Close();
            Global._YPF_Y40R_1?.Dispose();
            Global._YPF_Y40R_2?.Dispose();
            Global._qjxPwm16?.Close();
            Global._qjxPwm4?.Close();
            Global._ZH44242G14F2_Voltage?.Disconnect();
            Global._ZH44242G14F2_Current?.Disconnect();
        }

        /// <summary>
        /// 输出日志的方法，同时会输出到界面上和本地log里
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="level"></param>
        public void UpdateMessageo(string msg, LogLevel level = LogLevel.Info, [CallerMemberName] string propertyName = null)
        {
            lock (_updateMessageLock)
            {
                try
                {
                    string nameMsg = "";
                    if (Global._User != null)
                    {
                        nameMsg = Global._User.UserName + " : ";
                    }

                    MsgInfo msgInfo = new MsgInfo()
                    {
                        Timestamp = DateTime.Now.ToString("HH:mm:ss"),
                        Message = msg,
                    };

                    switch (level)
                    {
                        case LogLevel.Debug:
                            {
                                msgInfo.FontWeight = FontWeights.Normal;
                                msgInfo.Color = new SolidColorBrush(Colors.White);
                                Application.Current.Dispatcher.Invoke(() =>
                                {
                                    MessageLists.Add(msgInfo);
                                });
                                MyLog.Debug(nameMsg + msg, null, propertyName);
                                break;
                            }
                        case LogLevel.Info:
                            {
                                msgInfo.FontWeight = FontWeights.Normal;
                                msgInfo.Color = new SolidColorBrush(Colors.White);
                                Application.Current.Dispatcher.Invoke(() =>
                                {
                                    MessageLists.Add(msgInfo);
                                });
                                MyLog.Info(nameMsg + msg, null, propertyName);
                                break;
                            }
                        case LogLevel.Error:
                            {
                                msgInfo.FontWeight = FontWeights.Bold;
                                msgInfo.Color = new SolidColorBrush(Colors.Red);
                                Application.Current.Dispatcher.Invoke(() =>
                                {
                                    MessageLists.Add(msgInfo);
                                });

                                MyLog.Error(new Exception(nameMsg + msg), "", propertyName);
                                break;
                            }
                        default: break;
                    }

                    Application.Current.Dispatcher.Invoke(() =>
                     {
                         _homeView.MessageBoxLists.ScrollIntoView(msgInfo);
                     });
                }
                catch (Exception e)
                {
                    MyLog.Error(e);
                    MessageBox.Show("打印日志出现异常");
                }
            }
        }

        public void UpdateMessage(string msg, LogLevel level = LogLevel.Info, [CallerMemberName] string propertyName = null)
        {
            lock (_updateMessageLock)
            {
                try
                {
                    string nameMsg = Global._User?.UserName + " : ";

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        // 创建并添加消息
                        var msgInfo = new MsgInfo()
                        {
                            Timestamp = DateTime.Now.ToString("MM:dd:HH:mm:ss"),
                            Message = msg,
                            FontWeight = level == LogLevel.Error ? FontWeights.Bold : FontWeights.Normal,
                            Color = level == LogLevel.Error ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.White)
                        };
                        MessageLists.Add(msgInfo);

                        // 滚动到最新消息
                        if (_homeView?.MessageBoxLists != null)
                        {
                            _homeView.MessageBoxLists.ScrollIntoView(msgInfo);
                        }
                    });

                    // 记录日志（非UI操作，无需Dispatcher）
                    switch (level)
                    {
                        case LogLevel.Debug: MyLog.Debug(nameMsg + msg, null, propertyName); break;
                        case LogLevel.Info: MyLog.Info(nameMsg + msg, null, propertyName); break;
                        case LogLevel.Error: MyLog.Error(new Exception(nameMsg + msg), null, propertyName); break;
                    }
                }
                catch (Exception e)
                {
                    MyLog.Error(e);
                    MessageBox.Show("打印日志出现异常");
                }
            }
        }

        /// <summary>
        /// 显示最下栏产品序列号，到期日期，Task显示当前时间
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ShowProdeceLisence(string sn, string msg)
        {
            produceSn = sn;
            if (msg.Split(",").Length > 0)
            {
                produceDatetime = msg.Split(",")[0];
                produceDays = msg.Split(",")[1];
            }
            DateTime Finallytime = Convert.ToDateTime(produceDatetime);
            if (DateTime.Now > Finallytime)
            {
                //超时，软件不能用了
                Global._Lisence = true;
            }
            //开启线程显示当前时间
            Task.Run(new Action(async () =>
            {
                try
                {
                    while (true)
                    {
                        if (!_showTimeTaskTokenSource.Token.IsCancellationRequested)
                        {
                            NowTiming = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            //顺带定时备份文件
                            //操作
                            DateTime Finallytime = Convert.ToDateTime(produceDatetime);
                            if (DateTime.Now > Finallytime)
                            {
                                //超时，软件不能用了
                                Global._Lisence = true;
                            }
                            if (Global._isInit)
                            {
                                //读取总产能
                                int allcap = SqlSugarHelper.SqlReadByYear("ALLcapacity", true);
                                //读取当月产能
                                int monthcap = SqlSugarHelper.SqlReadByYear(DateTime.Now.Year.ToString() + "capacity", false);
                                //更新
                                ALLCapacity = "历史产能:" + allcap.ToString();
                                MonthCapacity = "当月产能:" + monthcap.ToString();
                            }
                        }
                        else
                        {
                            //线程被取消，退出线程
                            break;
                        }

                        await Task.Delay(1000, _showTimeTaskTokenSource.Token);
                    }
                }
                catch (Exception ex)
                {
                    UpdateMessage(ex.Message, LogLevel.Error);
                }
            }), _showTimeTaskTokenSource.Token);
        }

        private int _okCount = 0;
        private int _ngCount = 0;

        /// <summary>
        /// 刷新饼状图
        /// </summary>
        private void UpdateChart()
        {
            try
            {
                PieSeries = new SeriesCollection
                {
                    new PieSeries
                    {
                        Title = "合格 (OK)",
                        Values = new ChartValues<int> { _okCount },
                        Fill = System.Windows.Media.Brushes.LimeGreen,
                        Stroke = System.Windows.Media.Brushes.DarkGreen,
                        StrokeThickness = 2,
                        DataLabels = true,
                        Foreground = new SolidColorBrush(Colors.White),
                        LabelPoint = p => $"{p.Y} ({p.Participation:P0})"
                    },
                    new PieSeries
                    {
                        Title = "不合格 (NG)",
                        Values = new ChartValues<int> { _ngCount },
                        Fill = System.Windows.Media.Brushes.OrangeRed,
                        Stroke = System.Windows.Media.Brushes.DarkRed,
                        StrokeThickness = 2,
                        DataLabels = true,
                        LabelPoint = p => $"{p.Y} ({p.Participation:P0})"
                    }
                };
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 更新饼状图数据
        /// </summary>
        /// <param name="ok"></param>
        /// <param name="ng"></param>
        public void UpdateChartData(int ok, int ng)
        {
            try
            {
                _okCount = ok;
                _ngCount = ng;
                UpdateChart();
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="num"></param>
        /// <param name="isOK"></param>
        public void UpdateData(int num, bool isOK)
        {
            try
            {
                if (isOK)
                {
                    //饼状图刷新OK数据
                    _okCount += num;
                }
                else
                {
                    //饼状图刷新NG数据
                    _ngCount += num;
                }
                UpdateChart();
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        #endregion 普通方法
    }
}